document.addEventListener('DOMContentLoaded', function() {
    // 文件上传预览
    document.getElementById('photo').addEventListener('change', function(e) {
        const fileName = e.target.files[0]?.name || '选择文件';
        e.target.nextElementSibling.textContent = fileName;
    });

    // 表单验证和提交
    document.getElementById('employeeForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const formData = {
            name: document.getElementById('empName').value,
            department: document.getElementById('department').value,
            position: document.getElementById('position').value,
            hireDate: document.getElementById('hireDate').value,
            phone: document.getElementById('phone').value,
            photo: document.getElementById('photo').files[0]|| null
        };

        // 手机号码格式验证
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(formData.phone)) {
            alert('请输入正确的手机号码');
            return;
        }

        // TODO: 发送数据到服务器
        console.log('提交的员工数据:', formData);

        // 关闭模态框并重置表单
        $('#employeeModal').modal('hide');
        e.target.reset();
        document.querySelector('.custom-file-label').textContent = '选择文件';
    });

    // 删除确认
    let employeeToDelete = null;
    
    // 点击删除按钮时显示确认框
    document.querySelectorAll('.btn-danger').forEach(btn => {
        btn.addEventListener('click', function() {
            employeeToDelete = this.closest('tr');
            $('#deleteModal').modal('show');
        });
    });

    // 确认删除
    document.querySelector('#deleteModal .btn-danger').addEventListener('click', function() {
        if (employeeToDelete) {
            // TODO: 发送删除请求到服务器
            employeeToDelete.remove();
            employeeToDelete = null;
        }
        $('#deleteModal').modal('hide');
    });

    // 编辑员工信息
    document.querySelectorAll('.btn-info').forEach(btn => {
        btn.addEventListener('click', function() {
            const row = this.closest('tr');
            const cells = row.cells;
            // 填充表单数据
            document.getElementById('name').value = cells[1].textContent;
            document.getElementById('department').value = cells[2].textContent;
            document.getElementById('position').value = cells[3].textContent;
            document.getElementById('hireDate').value = cells[4].textContent;
            document.getElementById('phone').value = cells[5].textContent;
        });
    });
});